// pages/student/transcript/transcript.js
const app = getApp();
const { ocr, upload } = require("../../../utils/api");
const TranscriptParser = require("../../../utils/transcriptParser");

Page({
  data: {
    selectedImage: "",
    uploading: false,
    recognitionResult: null,
    transcriptList: [],
    imageUploaded: false, // 图片是否已上传
    uploadedImageUrl: "", // 上传后的图片URL
  },

  onLoad() {
    this.loadTranscriptList();
  },

  onShow() {
    this.loadTranscriptList();
  },

  async loadTranscriptList() {
    try {
      const local = require("../../../utils/local");
      const result = local.getTranscriptList();
      if (result.success) {
        this.setData({ transcriptList: result.data });
      }
    } catch (error) {
      console.error("加载成绩单列表失败:", error);
    }
  },

  // 远程方法移除，改为本地

  chooseImage() {
    wx.chooseMedia({
      count: 1,
      mediaType: ["image"],
      sourceType: ["album", "camera"],
      success: (res) => {
        const tempFilePath = res.tempFiles[0].tempFilePath;
        this.setData({ selectedImage: tempFilePath });
      },
      fail: (error) => {
        console.error("选择图片失败:", error);
        wx.showToast({
          title: "选择图片失败",
          icon: "error",
        });
      },
    });
  },

  removeImage() {
    this.setData({
      selectedImage: "",
      recognitionResult: null,
      imageUploaded: false,
      uploadedImageUrl: "",
    });
  },

  // 上传图片（不进行OCR识别）
  async uploadImage() {
    if (!this.data.selectedImage) return;

    this.setData({ uploading: true });

    try {
      // 上传图片到OSS
      wx.showLoading({ title: "正在上传图片..." });
      const uploadRes = await upload.uploadImage(this.data.selectedImage);
      console.log("图片上传成功:", uploadRes);
      wx.hideLoading();

      // 保存上传结果
      this.setData({
        imageUploaded: true,
        uploadedImageUrl: uploadRes.url,
      });

      wx.showToast({
        title: "图片上传成功，点击开始识别",
        icon: "success",
        duration: 3000,
      });
    } catch (error) {
      console.error("图片上传失败:", error);
      wx.hideLoading();

      // 根据错误类型显示不同的提示
      let errorMessage = "图片上传失败";
      if (error.message.includes("网络")) {
        errorMessage = "网络连接失败，请检查网络";
      } else {
        errorMessage = error.message || "图片上传失败，请重试";
      }

      wx.showToast({
        title: errorMessage,
        icon: "error",
        duration: 3000,
      });
    } finally {
      this.setData({ uploading: false });
    }
  },

  // 开始OCR识别
  async startOCR() {
    if (!this.data.imageUploaded || !this.data.uploadedImageUrl) {
      wx.showToast({
        title: "请先上传图片",
        icon: "none",
      });
      return;
    }

    this.setData({ uploading: true });

    try {
      // 调用OCR识别
      wx.showLoading({ title: "正在识别成绩单..." });
      const ocrRes = await ocr.recognizeTranscript(this.data.uploadedImageUrl);
      console.log("OCR识别结果:", ocrRes);
      wx.hideLoading();

      // 检查OCR识别结果
      console.log("OCR响应状态:", ocrRes?.code);
      console.log("OCR响应消息:", ocrRes?.message);

      if (!ocrRes) {
        throw new Error("OCR识别无响应");
      }

      if (ocrRes.code !== 0) {
        console.error("OCR识别失败:", ocrRes);
        throw new Error(`OCR识别失败: ${ocrRes.message || "未知错误"}`);
      }

      if (!ocrRes.data) {
        console.error("OCR识别结果为空:", ocrRes);
        throw new Error("OCR识别结果为空");
      }

      console.log("OCR识别数据:", ocrRes.data);

      // 解析OCR结果
      const parser = new TranscriptParser();
      const parsedData = parser.parseOcrResult(ocrRes.data);
      const formattedData = parser.formatForDisplay(parsedData);

      // 保存解析后的数据
      this.setData({
        recognitionResult: formattedData,
        rawOcrData: ocrRes,
      });

      wx.showToast({
        title: "识别成功",
        icon: "success",
        duration: 2000,
      });
    } catch (error) {
      console.error("OCR识别失败:", error);
      wx.hideLoading();

      // 根据错误类型显示不同的提示
      let errorMessage = "OCR识别失败";
      if (error.message.includes("识别失败")) {
        errorMessage = "OCR识别失败，请检查图片清晰度";
      } else if (error.message.includes("网络")) {
        errorMessage = "网络连接失败，请检查网络";
      } else {
        errorMessage = error.message || "OCR识别失败，请重试";
      }

      wx.showToast({
        title: errorMessage,
        icon: "error",
        duration: 3000,
      });
    } finally {
      this.setData({ uploading: false });
    }
  },

  // 使用测试图片
  async testWithSampleImage() {
    this.setData({ uploading: true });

    try {
      // 使用测试图片URL
      const testImageUrl =
        "https://srs-ocr.oss-cn-guangzhou.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20251006170243.jpg?Expires=1759809927&OSSAccessKeyId=TMP.3Krex2WMqT1Rdktmn9JaXhguzeL4rypmsiBQWyK4meZ63BxJuWsfJV38xBXts1qTwMrNT5tncoW6rEqUqDtXUumF3qoSgu&Signature=9sNA6Z5IG8AWa0I480trH0bXRn0%3D";

      // 模拟上传成功
      this.setData({
        selectedImage: testImageUrl,
        imageUploaded: true,
        uploadedImageUrl: testImageUrl,
      });

      wx.showToast({
        title: "已加载测试图片",
        icon: "success",
        duration: 1500,
      });

      // 等待一下再开始OCR识别
      await new Promise((resolve) => setTimeout(resolve, 1500));

      // 直接进行OCR识别
      wx.showLoading({ title: "正在识别成绩单..." });
      const ocrRes = await ocr.recognizeTranscript(testImageUrl);
      console.log("OCR识别结果:", ocrRes);
      wx.hideLoading();

      // 检查OCR识别结果
      console.log("OCR响应状态:", ocrRes?.code);
      console.log("OCR响应消息:", ocrRes?.message);

      if (!ocrRes) {
        throw new Error("OCR识别无响应");
      }

      if (ocrRes.code !== 0) {
        console.error("OCR识别失败:", ocrRes);
        throw new Error(`OCR识别失败: ${ocrRes.message || "未知错误"}`);
      }

      if (!ocrRes.data) {
        console.error("OCR识别结果为空:", ocrRes);
        throw new Error("OCR识别结果为空");
      }

      console.log("OCR识别数据:", ocrRes.data);

      // 解析OCR结果
      const parser = new TranscriptParser();
      const parsedData = parser.parseOcrResult(ocrRes.data);
      const formattedData = parser.formatForDisplay(parsedData);

      // 保存解析后的数据
      this.setData({
        recognitionResult: formattedData,
        rawOcrData: ocrRes,
      });

      wx.showToast({
        title: "识别成功",
        icon: "success",
        duration: 2000,
      });
    } catch (error) {
      console.error("测试图片处理失败:", error);
      wx.hideLoading();
      wx.showToast({
        title: "测试图片处理失败",
        icon: "error",
        duration: 3000,
      });
    } finally {
      this.setData({ uploading: false });
    }
  },

  // 测试环境变量
  async testEnvironment() {
    this.setData({ uploading: true });

    try {
      wx.showLoading({ title: "测试环境中..." });

      const res = await new Promise((resolve, reject) => {
        wx.cloud.callFunction({
          name: "test-env",
          success: (res) => {
            resolve(res.result);
          },
          fail: (error) => {
            reject(error);
          },
        });
      });

      wx.hideLoading();

      console.log("环境测试结果:", res);

      wx.showModal({
        title: "环境测试结果",
        content: `AccessKeyId: ${
          res.data.hasAccessKeyId ? "已配置" : "未配置"
        }\nAccessKeySecret: ${
          res.data.hasAccessKeySecret ? "已配置" : "未配置"
        }`,
        showCancel: false,
      });
    } catch (error) {
      wx.hideLoading();
      console.error("环境测试失败:", error);
      wx.showToast({
        title: "环境测试失败",
        icon: "error",
      });
    } finally {
      this.setData({ uploading: false });
    }
  },

  // 远程上传/识别方法删除，改为本地模拟

  editResult() {
    wx.navigateTo({
      url: `/pages/student/transcript/edit/edit?data=${encodeURIComponent(
        JSON.stringify(this.data.recognitionResult)
      )}`,
    });
  },

  async confirmResult() {
    if (!this.data.recognitionResult) return;

    wx.showLoading({ title: "保存中..." });

    try {
      const local = require("../../../utils/local");
      const result = local.saveTranscript(this.data.recognitionResult);
      if (result.success) {
        wx.showToast({
          title: "保存成功",
          icon: "success",
        });

        // 清空当前数据
        this.setData({
          selectedImage: "",
          recognitionResult: null,
        });

        // 刷新列表
        this.loadTranscriptList();
      } else {
        wx.showToast({
          title: result.message || "保存失败",
          icon: "error",
        });
      }
    } catch (error) {
      console.error("保存成绩单失败:", error);
      wx.showToast({
        title: "网络错误，请重试",
        icon: "error",
      });
    } finally {
      wx.hideLoading();
    }
  },

  // 保存远程方法删除

  onViewTranscript(e) {
    const id = e.currentTarget.dataset.id;
    if (!id) return;
    wx.navigateTo({ url: "/pages/student/transcript/detail/detail" });
  },

  onEditTranscript(e) {
    const id = e.currentTarget.dataset.id;
    if (!id) return;
    const local = require("../../../utils/local");
    const t = local.getTranscript();
    if (!t) return;
    wx.navigateTo({
      url: `/pages/student/transcript/edit/edit?data=${encodeURIComponent(
        JSON.stringify(t)
      )}`,
    });
  },

  onRevokeTranscript(e) {
    const id = e.currentTarget.dataset.id;
    if (!id) return;
    wx.showModal({
      title: "确认撤回",
      content: "撤回后将删除当前成绩单，是否继续？",
      success: (r) => {
        if (r.confirm) {
          const local = require("../../../utils/local");
          const result = local.removeTranscript();
          if (result.success) {
            wx.showToast({ title: "已撤回", icon: "success" });
            this.loadTranscriptList();
          }
        }
      },
    });
  },
});
